<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>更新库存</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div class="item-info">
          <p><strong>物品名称:</strong> {{ item.name }}</p>
          <p><strong>当前库存:</strong> {{ item.stockNum }} {{ item.unit }}</p>
        </div>
        <div class="form-group">
          <label>操作类型</label>
          <div class="operation-type-selector">
            <label class="radio-label">
              <input type="radio" v-model="operationType" :value="0" name="operationType">
              <span>入库</span>
            </label>
            <label class="radio-label">
              <input type="radio" v-model="operationType" :value="1" name="operationType">
              <span>出库</span>
            </label>
          </div>
        </div>
        <div class="form-group">
          <label for="quantity">{{ operationType === 0 ? '入库' : '出库' }}数量</label>
          <input
            id="quantity"
            v-model="quantity"
            type="number"
            min="1"
            :max="operationType === 1 ? Number(item.stockNum) : undefined"
            :placeholder="`请输入${operationType === 0 ? '入库' : '出库'}数量`"
            :class="{ 'error': showError && !isValidQuantity }"
          >
          <div class="error-message" v-if="showError && !isValidQuantity">
            请输入有效的{{ operationType === 0 ? '入库' : '出库' }}数量{{ operationType === 1 ? `（1-${item.stockNum}）` : '' }}
          </div>
        </div>
        <div class="form-group">
          <label for="reason">操作原因</label>
          <textarea
            id="reason"
            v-model="reason"
            :placeholder="`请输入${operationType === 0 ? '入库' : '出库'}原因（选填）`"
            rows="3"
          ></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button 
          class="submit-btn" 
          @click="handleSubmit"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : operationType === 0 ? '确认入库' : '确认出库' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import type { InventoryItem } from '../../types/inventory';
import { useInventoryStore } from '../../stores/inventoryStore';
import { ToastService } from '../../utils/toastService';

// 定义props
const props = defineProps<{
  show: boolean;
  item: InventoryItem;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'inventory-update-success', quantity: number, operationType: number): void;
}>();

const inventoryStore = useInventoryStore();

// 表单数据
const operationType = ref<number>(1); // 默认为出库操作
const quantity = ref<number>(1);
const reason = ref('');
const isSubmitting = ref(false);
const showError = ref(false);

// 计算属性：验证数量是否有效
const isValidQuantity = computed(() => {
  const qty = quantity.value;
  // 入库操作只需要数量大于0
  if (operationType.value === 0) {
    return qty && qty > 0;
  }
  // 出库操作需要数量大于0且不超过当前库存
  return qty && qty > 0 && qty <= Number(props.item.stockNum);
});

// 关闭模态框
const handleClose = () => {
  // 重置表单
  operationType.value = 1; // 默认为出库
  quantity.value = 1;
  reason.value = '';
  showError.value = false;
  emit('close');
};

// 提交表单
const handleSubmit = async () => {
  // 显示验证错误
  showError.value = true;
  
  // 验证表单
  if (!isValidQuantity.value) {
    return;
  }

  isSubmitting.value = true;
  try {
    // 使用store进行库存更新操作
    const result = await inventoryStore.updateInventory(
      props.item.id, 
      quantity.value, 
      operationType.value
    );
    
    if (result.success) {
      // 操作成功
      handleClose();
      emit('inventory-update-success', quantity.value, operationType.value);
    } else {
      ToastService.error(`${operationType.value === 0 ? '入库' : '出库'}失败: ${result.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('库存更新请求失败:', error);
    ToastService.error(`${operationType.value === 0 ? '入库' : '出库'}失败，请检查网络连接`);
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.item-info {
  margin-bottom: 20px;
  padding: 12px;
  background-color: #f9fafb;
  border-radius: 6px;
}

.item-info p {
  margin: 8px 0;
  color: #374151;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-group input.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.submit-btn {
  background: #1890ff;
  border: none;
  color: white;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.operation-type-selector {
  display: flex;
  gap: 20px;
  margin-top: 8px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.radio-label input {
  margin: 0;
  cursor: pointer;
}

.radio-label span {
  font-size: 14px;
  color: #333;
}
</style>